<?php
namespace app\controllers;

use Yii;
use app\models\MobileAdspace;

use app\services\AppService;

class AppController extends AuthController
{
    public $currentHeader = 'header-operation';
    public $currentNav = 'app-list-nav';
    public $pageTitle = '';

    public function init()
    {
        parent::init();
        $this->service = new AppService();
    }

    public function actionAppList()
    {
        return $this->show();
    }

    public function actionGetAppList()
    {
        $apps = $this->service->getAppList();
        return $this->jsonReturn(['data' => $apps]);
    }

    public function actionGetAppAdspace()
    {
        $appId = $this->I('id');
        $ads = $this->service->getAppAdspaces($appId);
        return $this->jsonReturn($ads);
    }

    public function actionEdit()
    {
        $appId = $this->I('id');
        $app = $this->getOne('ResourceApp', ['id' => $appId]);
        $this->app = $app;
        $ads = $this->service->getAppAdspaces($appId);
        $this->adspaces = $ads;
        list($formats, $size) = $this->service->getAdspaceSizeAndFormats($ads);
        $this->formats = $formats;
        $this->size = $size;
        return $this->show('editApp');
    }

    public function actionNew()
    {
        return $this->show('newApp');
    }

    public function actionSaveApp()
    {
        $app = $this->I();
        $saved = $this->service->trySave($app);
        if (isset($saved['id'])) {
            $appId = $saved['id'];
            $adspaceIds = $this->I('adspace_ids');
            if ($this->service->saveAppAdspaceMap($appId, $adspaceIds)) {
                $saved = $this->t('pack', 'App saved!');
                $this->ok($saved);
            }
        }
        $saved = $this->t('pack', 'App save failed!');
        $this->ng($saved);
    }

    public function actionUploadAdsPic()
    {
        $this->service->uploadAdsPic();
    }

    public function actionGetUnbindAdspace()
    {
        $type = $this->I('type');
        $key = $this->I('search');
        $unbindAds = $this->service->getUnbindAdspace($key, $type);
        $this->jsonReturn(['items' => $unbindAds]);
    }

    public function actionGetAdspaceSizeAndFormats()
    {
        list($formats, $size) = $this->service->getAdspaceSizeAndFormats($this->I('app'));
        $this->ok(['sizeList' => $size, 'formatList' => $formats]);
    }
}//eof

